package com.akaovi.chatroom.scene;

import com.akaovi.chatroom.client.Client;
import com.akaovi.chatroom.mess.MessType;
import com.akaovi.chatroom.mess.Register;
import com.akaovi.chatroom.mess.ResponseStatus;
import com.akaovi.chatroom.utils.CommonUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author akaovi
 * @version 1.0
 * @description 注册
 * @date 2022/12/9 0:23
 * @since 2022/12/9 0:23
 */
public class RegisterScene {
    static VBox registerVBox = new VBox();
    static Label textRegister = new Label("注册");
    static TextField registerUserName = new TextField();
    static PasswordField registerPwd = new PasswordField();
    static PasswordField conformPwd = new PasswordField();
    static Button conformRegisterBtn = new Button("注册");
    static Button cancelRegisterBtn = new Button("取消");
    static HBox hBox = new HBox();
    static Scene registerScene = new Scene(registerVBox, LoginScene.loginWidth, LoginScene.loginHeight);

    private static final String regEx = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])(.{8,16})$";

    static {
        // 注册界面初始化
        registerVBox.setAlignment(Pos.CENTER);
        registerVBox.setSpacing(20);
        textRegister.setFont(new Font(20));
        registerUserName.setPromptText("请输入用户名: ");
        registerUserName.setFocusTraversable(false);
        registerUserName.setMaxWidth(200);
        registerPwd.setPromptText("请输入密码: ");
        registerPwd.setFocusTraversable(false);
        registerPwd.setMaxWidth(200);
        conformPwd.setPromptText("请确认密码: ");
        conformPwd.setFocusTraversable(false);
        conformPwd.setMaxWidth(200);
        hBox.getChildren().addAll(conformRegisterBtn, cancelRegisterBtn);
        hBox.setSpacing(20);
        hBox.setAlignment(Pos.CENTER);
        registerVBox.getChildren().addAll(textRegister, registerUserName, registerPwd, conformPwd, hBox);

        // 绑定注册事件
        conformRegisterBtn.setOnAction(e -> {
            if (CommonUtils.isAnyEmpty(conformPwd.getText(), registerPwd.getText())) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("注册失败");
                alert.setContentText("密码不能为空!");
                System.out.println(1);
                return;
            }
            if (!registerPwd.getText().equals(conformPwd.getText())) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("注册失败");
                alert.setContentText("两次输入的密码不相同!");
                System.out.println(2);
                return;
            }
            if (!isOkPassword(registerPwd.getText())) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("注册失败");
                alert.setContentText("密码中必须包含字母、数字、特称字符，至少8个字符，最多16个字符!");
                System.out.println(3);
                return;
            }
            RegisterScene.sendToRegister(registerUserName.getText(), registerPwd.getText());
        });

        cancelRegisterBtn.setOnAction(e -> {
            LoginScene.changeToLoginScene();
            System.out.println("注册的取消按钮");
        });
    }

    /**
     * 密码中必须包含字母、数字、特称字符，至少8个字符，最多16个字符
     *
     * @param password 密码
     * @return true 符合
     */
    public static boolean isOkPassword(String password) {
        Pattern Password_Pattern = Pattern.compile(regEx);
        Matcher matcher = Password_Pattern.matcher(password);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    /**
     * 转到注册场景
     */
    public static void changeToRegisterScene() {
        Client.getStage().setScene(RegisterScene.registerScene);
    }

    /**
     * 注册
     *
     * @param username username
     * @param pwd      pwd
     */
    private static void sendToRegister(String username, String pwd) {
        System.out.println("注册");
        System.out.println(username + pwd);
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            // 创建socket
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 20000);
            // 发送注册请求
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(new Register(MessType.Register, username, CommonUtils.getMd5(pwd + LoginScene.SALT)));
            oos.flush();
            // 接收ReRegister 判断是否登录成功
            ois = new ObjectInputStream(socket.getInputStream());
            ResponseStatus mess = (ResponseStatus) ois.readObject();
            if (mess.getStatus() != 200) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("注册失败");
                alert.setContentText(mess.getDetails());
            } else {
                SuccessRegisterScene.changeToSuccessRegisterScene(mess.getDetails());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CommonUtils.closeResource(socket, oos, ois);
        }
    }

}
